class ProjectToUsersController < ApplicationController
  def new
    @cid = current_user.company_pid 
    @projects = Project.where(:company_id => @cid)
    @row_id = 1
    render :layout => nil
  end
  
  def create
      @paras = params[:items].split(",");
      rowCount = @paras[1].to_i
      success = 1
      index = 0
      offset = 2
      datasetlen = 3
      while index < rowCount
        @pu = ProjectToUser.new
        @pu.user_id = @paras[0].to_i
        @pu.project_id = @paras[offset+index*datasetlen]   
        @pu.rolename_id = @paras[offset+index*datasetlen+1]
        @pu.percentage_id = @paras[offset+index*datasetlen+2]
        if !@pu.save
          success = 0
        end
        index = index + 1
      end
      render :text => success
  end
  
  def edit
    @user_id = params[:id]
    @cid = current_user.company_pid
    @projects = Project.where("company_id" => @cid)
    @ptu = ProjectToUser.where("user_id" => @user_id)
    @rows = @ptu.count
    render :layout => nil
  end
  
  def delete
    @paras = params[:items].split(",")
    count = @paras.count
    success = 1
    i = 0
    while i < count
      @entries = ProjectToUser.find_all_by_user_id(@paras[i])
      @entries.each do |entry|
        entry.destroy
      end
      i = i + 1
    end
    render :text => success
  end
  
  def update
    @paras = params[:items].split(",")
    user_id = @paras[0].split("_")[1]
    @entries = ProjectToUser.find_all_by_user_id(user_id)
    @entries.each do |entry|
      entry.destroy
    end
    rowCount = @paras[1].to_i
    success = 1
    index = 0
    offset = 2
    datasetlen = 3
    while index < rowCount
      @pu = ProjectToUser.new
      @pu.user_id = user_id
      @pu.project_id = @paras[offset+index*datasetlen]   
      @pu.rolename_id = @paras[offset+index*datasetlen+1]
      @pu.percentage_id = @paras[offset+index*datasetlen+2]
      if !@pu.save
        success = 0
      end
      index = index + 1
    end
    render :text => success   
  end
end
